#!/usr/bin/env python

# face database available at http://cswww.essex.ac.uk/mv/allfaces/faces95.zip
# unzip and enter the path below:
source = '../faces95'

# number of different people
people = 30
# numer of templates per person
templates = 5
# number of different photos
photos = 200


from subprocess import call
call(["rm ./templates/* -rf"], shell=True)
call(["rm ./photos/* -rf"], shell=True)
from os import listdir, mkdir
from os.path import isfile, join
from random import choice,sample
from shutil import copyfile
from re import match
directories = [ dir for dir in listdir(source) if not isfile(source+'/'+dir) ]
if people > len(directories):
    print "Not enough individuals. Will use only ", len(directories)
    people = len(directories)
directories = sample(directories,min(len(directories),people))
used = []
for directory in directories:
    mkdir('templates/'+directory)
    files = [ file for file in listdir(source+'/'+directory+'/') if isfile(source+'/'+directory+'/'+file) and file.startswith(directory) and file.endswith('.jpg')]
    files = sample(files,templates)
    for file in files:
        used.append(directory+'/'+file)
        #print './templates/'+directory+'/'+file
        copyfile(source+'/'+directory+'/'+file,'./templates/'+directory+'/'+file)

for i in xrange(photos):
    directory = choice(directories)
    files = [ file for file in listdir(source+'/'+directory+'/') if isfile(source+'/'+directory+'/'+file) and file.startswith(directory) and file.endswith('.jpg') and directory+'/'+file not in used ]
    file = choice(files)
    used.append(file)
    #print './photos/'+directory+'_'+file
    copyfile(source+'/'+directory+'/'+file,'./photos/'+directory+'_'+file)
